package com.tjw.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tjw.constant.RedisConstant;
import com.tjw.dao.CheckGroupDao;
import com.tjw.dao.CheckItemDao;
import com.tjw.dao.SetMealDao;
import com.tjw.entity.PageResult;
import com.tjw.entity.QueryPageBean;
import com.tjw.pojo.CheckGroup;
import com.tjw.pojo.CheckItem;
import com.tjw.pojo.Setmeal;
import com.tjw.service.SetMealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author tjw
 * @Date 2020/10/9
 */
@Service(interfaceClass = SetMealService.class)
public class SetMealServiceImpl implements SetMealService {

    @Autowired
    private SetMealDao setMealDao;
    @Autowired
    private CheckGroupDao checkGroupDao;
    @Autowired
    private CheckItemDao checkItemDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outPutPath;

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> pageInfo = setMealDao.pageQuery(queryString);
        return new PageResult(pageInfo.getTotal(), pageInfo.getResult());
    }

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setMealDao.add(setmeal);
        Integer id = setmeal.getId();
        setSetmealAndCheckgroup(checkgroupIds, id);
        if (setmeal.getImg() != null && setmeal.getImg().length() > 0) {
            //将图片保存到redis
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());
        }
        //当添加套餐后需要重新生成静态页面（套餐列表页面、套餐详情页面）
        generateMobileStaticHtml();
    }

    //生成当前方法所需的静态页面
    public void generateMobileStaticHtml() {
        //在生成静态页面之前需要查询数据
        List<Setmeal> list = setMealDao.findAll();

        //需要生成套餐列表静态页面
        generateMobileSetmealListHtml(list);

        //需要生成套餐详情静态页面
        generateMobileSetmealDetailHtml(list);
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> list) {
        Map map = new HashMap();
        //为模板提供数据，用于生成静态页面
        map.put("setmealList", list);
        generteHtml("mobile_setmeal.ftl", "m_setmeal.html", map);
    }

    //生成套餐详情静态页面（可能有多个）
    public void generateMobileSetmealDetailHtml(List<Setmeal> list) {
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal", setMealDao.findById(setmeal.getId()));
            generteHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", map);
        }
    }

    //通用的方法，用于生成静态页面
    public void generteHtml(String templateName, String htmlPageName, Map map) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();//获得配置对象
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            out = new FileWriter(new File(outPutPath + "/" + htmlPageName));
            //输出文件
            template.process(map, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        Integer id = setmeal.getId();
        setMealDao.edit(setmeal);
        setMealDao.deleteSetMealAndCheckGroupById(id);
        setSetmealAndCheckgroup(checkgroupIds, id);
        if (setmeal.getImg() != null && setmeal.getImg().length() > 0) {
            //将图片保存到redis
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());
        }
        //当编辑套餐后需要重新生成静态页面（套餐列表页面、套餐详情页面）
        generateMobileStaticHtml();
    }

    private void setSetmealAndCheckgroup(Integer[] checkgroupIds, Integer id) {
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                HashMap<String, Integer> map = new HashMap<>();
                map.put("setmeal_id", id);
                map.put("checkgroup_id", checkgroupId);
                setMealDao.setSetMealAndCheckGroup(map);
            }
        }
    }

    @Override
    public List<Setmeal> findAll() {
        return setMealDao.findAll();
    }

    @Override
    public Setmeal findById(Integer id) {
        //return setMealDao.findById(id);
        return findById2(id);
    }

    public Setmeal findById2(Integer id) {
        Setmeal setmeal = setMealDao.getById(id);
        List<CheckGroup> checkGroups = checkGroupDao.findById(id);
        for (CheckGroup checkGroup : checkGroups) {
            List<CheckItem> checkItems = checkItemDao.findById(checkGroup.getId());
            checkGroup.setCheckItems(checkItems);
        }
        setmeal.setCheckGroups(checkGroups);
        return setmeal;

    }

    @Override
    public Integer[] findCheckGroupById(Integer id) {
        return setMealDao.findCheckGroupById(id);
    }

    @Override
    public void delete(Integer id) {
        setMealDao.deleteSetMealAndCheckGroupById(id);
        setMealDao.delete(id);
        //当删除套餐后需要重新生成静态页面（套餐列表页面、套餐详情页面）
        generateMobileStaticHtml();
    }

    @Override
    public List<Map> getSetmealReport() {
        return setMealDao.getSetmealReport();
    }
}
